const app = getApp()
 //云数据库初始化
 const db = wx.cloud.database({});
 const cont = db.collection('gesture_list')

Page({
  data: {
    productId: app.globalData.productId,
    deviceName: app.globalData.deviceName,
    stateReported: {},
    gesture_list:[]
  }, 
  onLoad: function (options) {
    console.log("index onLoad")
    if (!app.globalData.productId) {
      wx.showToast({
        title: "产品ID不能为空",
        icon: 'none',
        duration: 3000
      })
      return
    } else if (!app.globalData.deviceName) {
      wx.showToast({
        title: "设备名称不能为空",
        icon: 'none',
        duration: 3000
      })
      return
    }
    // this.update()
    var _this=this;
    db.collection('gesture_list').get({
      success: res => {
        // console.log(res.data)
        // console.log(this)
        console.log(res.data[0]);
        this.setData({
          gesture_list:res.data
        })
      }
    })


  },

  // shouquan(){
  //   wx.requestSubscribeMessage({
  //     tmplIds: ['ocEq9xW-5a3NZ_gn4mbbIwZHeYNJqNTrJeKkf1c-3n0'],
  //   }).then(res=>{
  //     console.log('授权成功',res)
  //     //this.getOpenid()
  //   }).catch(res=>{
  //     console.log('授权失败',res)
  //   })
 // },
  //获取用户的openid
  getOpenid(){
    wx.cloud.callFunction({
      // name:"helloCloud",
      // 
      name:"getopenid",
      data:{
          message:'helloCloud',
        }
    }).then(res=>{
      console.log(res)//res就将appid和openid返回了
      let openid=res.result.openid
      console.log("获取openid成功",openid)
      this.send(openid)
    }).catch(res=>{
      console.log("获取openid失败",res)
    })
  },
  //发送模板消息到指定用户，推送之前要先获取用户的openid
  send(openid){
    wx.cloud.callFunction({
      name:"sendMsg",
      data:{
        openid:openid,
        
     },
      success(res){
        console.log("推送消息成功",res)
      },
      fail(res){
        console.log("推送消息失败",res)
      }
    })
  },

  update() {
    wx.showLoading()
    wx.cloud.callFunction({
      name: 'iothub-shadow-query',
      data: {
        ProductId: app.globalData.productId,
        DeviceName: app.globalData.deviceName,
        SecretId: app.globalData.secretId,
        SecretKey: app.globalData.secretKey,
      },
      success: res => {
        wx.showToast({
          icon: 'none',
          title: 'Subscribe完成，获取云端数据成功',
        })
        let deviceData = JSON.parse(res.result.Data)

        this.setData({
          stateReported: deviceData.payload.state.reported
        })
        console.log("result:", deviceData)
        
        db.collection('gesture_list').add({
          // data 字段表示需新增的 JSON 数据
          data: {
              day:deviceData.payload.state.reported.date,
              hour:deviceData.payload.state.reported.hour,
              minute:deviceData.payload.state.reported.minute,
              who:deviceData.payload.state.reported.update_who,
              piece:deviceData.payload.state.reported.update_piece,
          }
        })
        .then(res => {
          console.log(res)
        })

        if(deviceData.payload.state.reported.warning_nsee_cat)
            this.getOpenid();
        

      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: 'Subscribe失败，获取云端数据失败',
        })
        console.error('[云函数] [iotexplorer] 调用失败：', err)
      }
    })
  },
  switchChange(e) {
    let value = 0
    if (e.detail.value == true) {
      value = 1
    }
    let item = e.currentTarget.dataset.item
    let obj = {
      [`${item}`]: value
    }
    let payload = JSON.stringify(obj)
    JSON.parse
    console.log(payload)
    wx.showLoading()
    wx.cloud.callFunction({
      name: 'iothub-publish',
      data: {
        SecretId: app.globalData.secretId,
        SecretKey: app.globalData.secretKey,
        ProductId: app.globalData.productId,
        DeviceName: app.globalData.deviceName,
        Topic: app.globalData.productId + "/" + app.globalData.deviceName + "/msg/len_on",
        Payload: payload,
      },
      success: res => {
        wx.showToast({
          icon: 'none',
          title: 'publish完成',
        })
        console.log("res:", res)
        // if(result.payload.metedata.reported.warning_nsee_cat )
        // if(1)
        

      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: 'publish失败，请连接设备',
        })
        console.error('[云函数] [iotexplorer] 调用失败：', err)
      }
    })  
  },


  


//使用云函数



  go_fist: function(){
    wx.navigateTo({
      url: '/pages/TencentCloud/gesture_fist/gesture_fist',
    })
  },
  go_ok: function(){
    wx.navigateTo({
      url: '/pages/TencentCloud/gesture_ok/gesture_ok',
    })
  },
  go_plam: function(){
    wx.navigateTo({
      url: '/pages/TencentCloud/gesture_plam/gesture_plam',
    })
  },
  go_yes: function(){
    wx.navigateTo({
      url: '/pages/TencentCloud/gesture_yes/gesture_yes',
    })
  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  // data: {
  //   array: ['10g', '20g', '30g', '40g'],
  //   index: 0,
  //   date: '2016-09-01',
  //   time: '12:01'
  // },
  // bindPickerChange: function(e) {
  //   console.log('picker发送选择改变，携带值为', e.detail.value)
  //   this.setData({
  //     index: e.detail.value
  //   })
  // },
  


  
})


